package com.ninjas.module.error.controller;

import com.ninjas.module.error.domain.model.User;
import com.ninjas.module.error.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public PageInfo<User> list() {
        return userService.list(1, 2);
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody User user) {
        if (!userService.isUsernameAvailable(user.getUserName())) {
            return ResponseEntity.badRequest().body("用户名已存在");
        }
        userService.registerUser(user);
        return ResponseEntity.ok("注册成功");
    }

    // 用户登录接口
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");
        if (userService.authenticateUser(username, password)) {
            return ResponseEntity.ok("登录成功");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }
}
